import {
  LocalizationContext,
  LocalizationMap,
  Menu,
  MenuDivider,
  MenuItem,
  Popover,
  Position,
  SpecialZoomLevel,
  Toggle,
} from "../../core";

import { RenderZoomProps } from "./Zoom";
import { FC, ReactElement, useContext } from "react";

const LEVELS = [0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4];
const PORTAL_OFFSET = { left: 0, top: 8 };

const ZoomPopover: FC<RenderZoomProps> = ({ scale, onZoom }) => {
  const l10n = useContext(LocalizationContext);

  const getSpecialLevelLabel = (
    level: SpecialZoomLevel
  ): string | LocalizationMap => {
    switch (level) {
      case SpecialZoomLevel.ActualSize:
        return l10n && l10n.zoom ? l10n.zoom.actualSize : "Actual size";
      case SpecialZoomLevel.PageFit:
        return l10n && l10n.zoom ? l10n.zoom.pageFit : "Page fit";
      case SpecialZoomLevel.PageWidth:
        return l10n && l10n.zoom ? l10n.zoom.pageWidth : "Page width";
    }
  };

  const renderTarget = (toggle: Toggle): ReactElement => {
    const click = (): void => {
      toggle();
    };
    return (
      <span className="rpv-zoom__popover-target" onClick={click}>
        <span className="rpv-zoom__popover-target-scale">
          {Math.round(scale * 100)}%
        </span>
        <span className="rpv-zoom__popover-target-arrow" />
      </span>
    );
  };

  const renderContent = (toggle: Toggle): ReactElement => (
    <Menu>
      {Object.keys(SpecialZoomLevel).map((k) => {
        const level = k as SpecialZoomLevel;
        const clickMenuItem = (): void => {
          toggle();
          onZoom(level);
        };
        return (
          <MenuItem key={level} onClick={clickMenuItem}>
            {getSpecialLevelLabel(level)}
          </MenuItem>
        );
      })}
      <MenuDivider />
      {LEVELS.map((level) => {
        const clickMenuItem = (): void => {
          toggle();
          onZoom(level);
        };
        return (
          <MenuItem key={level} onClick={clickMenuItem}>
            {`${Math.round(level * 100)}%`}
          </MenuItem>
        );
      })}
    </Menu>
  );

  return (
    <Popover
      position={Position.BottomCenter}
      target={renderTarget}
      content={renderContent}
      offset={PORTAL_OFFSET}
      closeOnClickOutside={true}
      closeOnEscape={true}
    />
  );
};

export default ZoomPopover;
